package com.example.waimai.service.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.waimai.dto.DishDto;
import com.example.waimai.mapper.DishMapper;
import com.example.waimai.pojo.Dish;
import com.example.waimai.pojo.DishFlavor;
import com.example.waimai.service.ServiceDish;
import com.example.waimai.service.ServiceDishFlavor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class ServiceImplDish extends ServiceImpl<DishMapper, Dish> implements ServiceDish {

    @Autowired
    private ServiceDishFlavor serviceDishFlavor;
    @Transactional//增加菜品
    public void saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);

        Long id = dishDto.getId();
        List<DishFlavor> flavors=dishDto.getFlavors();
        flavors.stream().map((item)->{
            item.setDishId(id);
            return item;
                }).collect(Collectors.toList());

        serviceDishFlavor.saveBatch(flavors);
    }

    @Override
    public DishDto updatadishWithFlavor(Long id) {
        //查询菜品基本信息
        Dish byId = this.getById(id);

        DishDto dishDto=new DishDto();
        BeanUtils.copyProperties(byId,dishDto);

        //
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,byId.getId());
        List<DishFlavor> list = serviceDishFlavor.list(lqw);

        dishDto.setFlavors(list);
        return  dishDto;
    }

    @Override
    public void updatasaveWithFlaver(DishDto dishDto) {
        //更新dish的基本信息
        this.updateById(dishDto);
        //清理当前菜品对应的口味数据  dish_flavor表的delete操作
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        lqw.eq(DishFlavor::getDishId,dishDto.getId());
        serviceDishFlavor.remove(lqw);

        //添加提交过来的口味数据 dish_flavor的insert操作

        List<DishFlavor> flavor=dishDto.getFlavors();
        flavor.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());//保存id

        serviceDishFlavor.saveBatch(flavor);
    }

    @Override
    @Transactional
    public void DeleteWithdish(List<Long> idsList) {
        this.removeByIds(idsList);
        LambdaQueryWrapper<DishFlavor> lqw=new LambdaQueryWrapper<>();
        for(Long id:idsList){
            lqw.eq(DishFlavor::getDishId,id);
            serviceDishFlavor.removeById(id);
        }
    }


}
